<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>proxy</title>
  </head>
  <body>
    <script>
      const person = {
        firstName: "li",
        lastName: "peiqi",
      };

      // Object.defineProperty(person, "fullName", {
      //   // writable: true,
      //   enumerable: true,
      //   configurable: true,
      //   get() {
      //     return this.firstName + " " + this.lastName;
      //   },
      //   set(val) {
      //     const [firstName, lastName] = val.split(" ");
      //     this.firstName = firstName;
      //     this.lastName = lastName;
      //   },
      // });

      // console.log(person.fullName);
      // person.fullName = "wang peiqi";
      // console.log(person);
      
      const proxyPerson = new Proxy(person, {
        // 代理person对象上属性的读取方法
        get: function (target, propKey, receiver) {
          /**
            target 代理的目标对象   
            propKey 当前访问的属性名
            receiver 返回的代理后的对象
          */
          if (propKey === "fullName") {
            return target.firstName + " " + target.lastName;
          }

          // return target[propKey];
          return Reflect.get(target, propKey, receiver);
        },
        // 代理person对象上属性的设置方法
        set: function (target, propKey, value, receiver) {
          if (propKey === "fullName") {
            const [firstName, lastName] = value.split(" ");
            // target.firstName = firstName;
            // target.lastName = lastName;
            Reflect.set(target, "firstName", firstName, receiver);
            Reflect.set(target, "lastName", lastName, receiver);
            return;
          }

          // target[propKey] = value;
          return Reflect.set(target, propKey, value, receiver);
        },
      });

      console.log(proxyPerson.fullName);
      proxyPerson.fullName = "wang pieqi";
      console.log(proxyPerson);
    </script>
  </body>
</html>
